{extend name="user:base" /}
{block name="title"}发布文章-富文本{/block}
{block name="main"}

<link rel="stylesheet" href="{:config('web.cdn')}/static/index/editormd/css/style.css" />
<link rel="stylesheet" href="{:config('web.cdn')}/static/index/editormd/css/editormd.css" />

<!-- begin::main content -->
<main class="main-content">
<div class="articleAdd">

	<div class="fly-panel fly-panel-user">
		<div class="layui-tab layui-tab-brief" lay-filter="user">
			<div class="layui-tab-content" style="padding: 20px 0;">
				<div class="layui-form layui-form-pane layui-tab-item layui-show">
					<form method="post" class="layui-form" onsubmit="return false">

						{notempty name='$article'}
						<input type="hidden"  name="id" autocomplete="off" value="{$article.id}" class="layui-input">
						{/notempty}

						<input type="hidden"  name="is_md" autocomplete="off" value="1" class="layui-input">



						<div class="layui-form-item">
							<div class="layui-input-inline artitle">
								<input placeholder="文章标题" type="text" id="L_email" name="title" required  autocomplete="off"
									   value="{notempty name='$article'}{$article.title}{/notempty}"
									   class="layui-input">
							</div>
						</div>



						<div class="alert alert-secondary alert-with-border alert-dismissible" role="alert">
							<i class="ti-announcement m-r-10"></i>
							F11键进入[退出]全屏专注模式编辑。
						</div>

						<div class="layui-form-item layui-form-text">

							<div class="layui-input-block">
								<div id="test-editormd">
									<textarea name="info" id="info" style="width:98%;height:600px;visibility:hidden;resize:none;">{notempty name='$article'}{$article.article.info}{/notempty}</textarea>
								</div>
							</div>
						</div>

						{empty name='$article'}
						<!--当修改文章时，屏蔽到原分类，避免分类错误-->
						<div class="layui-form-item" id="cate">
							<label for="L_city" class="layui-form-label">分类</label>
							<div class="layui-input-inline">
								<div id="cate1"></div>
							</div>

							<div class="layui-input-inline">
								<div id="cate2"></div>
							</div>
						</div>
						{/empty}

						{if isset($article)}
						<input type="hidden" name="cate_id" value="{$article.cate_id}">
						{/if}

						<div class="layui-form-item" id="img">
							<div class="layui-input-inline artitle">
								{empty name="$article"}
								{:uploader('prefimg')}
								{else /}
								{:uploader('prefimg',$article['prefimg'])}
								{/empty}
							</div>
						</div>

						{include file="article/users"}

						<div class="KmoreInfo">
							<div class="layui-form-item layui-form-text">
								<div class="layui-input-block">
									<textarea placeholder="用户积分下载或者查看" name="hidden_info" class="layui-textarea">{notempty name="$article"}{$article.hidden_info}{/notempty}</textarea>
								</div>
							</div>

							<div class="layui-form-item">
								<div class="layui-input-inline artitle">
									<input placeholder="查看隐藏信息所需积分"
										   type="number"
										   min="0"
										   max="100"
										   name="score"
										   value="{notempty name='$article'}{$article.score}{/notempty}"
										   class="layui-input">
								</div>
							</div>

							{if isset($index_user) && $index_user.is_admin == 1}
							<!--当发布者为后台管理员时可以操作-->
							<div class="layui-form-item">
								<label for="L_city" class="layui-form-label">点击量</label>
								<div class="layui-input-inline">
									{empty name="$article"}
									<input type="number" id="L_city" name="hits" autocomplete="off" value="{:rand(40,700)}" class="layui-input">
									{else /}
									<input type="number" id="L_city" name="hits" autocomplete="off" value="{$article.hits}" class="layui-input">
									{/empty}
								</div>
							</div>

							<div class="layui-form-item">
								<label for="L_city" class="layui-form-label">喜欢</label>
								<div class="layui-input-inline">
									{empty name="$article"}
									<input type="number"  name="like" autocomplete="off" value="{:rand(2,50)}" class="layui-input">
									{else /}
									<input type="number"  name="like" autocomplete="off" value="{$article.like}" class="layui-input">
									{/empty}
								</div>
							</div>
							<!--是否推荐-->
							<div class="layui-form-item">
								<label for="L_city" class="layui-form-label">推荐</label>
								<div class="layui-input-inline">

									{empty name="$article"}
									<input type="radio" name="recommend" value="1" title="推荐" >
									<input type="radio" name="recommend" value="0" title="不推荐" checked="checked">
									{else /}
									<input type="radio" name="recommend" value="1" title="推荐" {if $article.recommend ==1}checked{/if}>
									<input type="radio" name="recommend" value="0" title="不推荐" {if $article.recommend ==0}checked{/if}>
									{/empty}
								</div>
							</div>

							<!--是否置顶-->
							<div class="layui-form-item">
								<label for="L_city" class="layui-form-label">置顶</label>
								<div class="layui-input-inline">

									{empty name="$article"}
									<input type="radio" name="top" value="1" title="置顶" >
									<input type="radio" name="top" value="0" title="不置顶" checked="checked">
									{else /}
									<input type="radio" name="top" value="1" title="置顶" {if $article.top ==1}checked{/if}>
									<input type="radio" name="top" value="0" title="不置顶" {if $article.top ==0}checked{/if}>
									{/empty}
								</div>
							</div>

							{/if}
						</div>



						<!--当发布者为后台管理员时可以操作-->
						<div class="layui-form-item">
							<button class="layui-btn" key="set-mine" lay-submit lay-filter="info">提交保存</button>
							<button class="layui-btn" key="set-mine" lay-submit lay-filter="draft">保存草稿</button>
						</div>
					</form>
				</div>
			</div>

		</div>
	</div>
</div>
</main>

<script src="{:config('web.cdn')}/static/index/editormd/editormd.js"></script>

<script type="text/javascript">

	//图片上传js
	//md 编辑器
	var testEditor;
	$(function() {
		testEditor = editormd("test-editormd", {
			width           : "100%",
			height:'650px',
			//autoHeight      : true,
			path            : "{:config('web.cdn')}/static/index/editormd/lib/",
			imageUpload    : true,
			imageFormats   : ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
			imageUploadURL : "{:url('Upload/mdeditor')}",
			htmlDecode      : "style,script,iframe",
			tex             : true,
			emoji           : true,
			taskList        : true,
			flowChart       : true,
			sequenceDiagram : true,
			onload : function() {
				// alert("onload");
				// this.setMarkdown("### onloaded");
				// console.log("onload =>", this, this.id, this.settings);
				//编辑器 拖拽上传
				var codeEditor = $(".CodeMirror")[0];
				codeEditor.ondragenter = function(e) {
				  e.preventDefault();
				  e.stopPropagation();
				  console.log("dragenter");
				  return false;
				};
				codeEditor.ondragover = function(e) {
				  e.preventDefault();
				  e.stopPropagation();
				  console.log("dragover");
				  return false;
				};
				codeEditor.ondrop = function(e) {
				  e.preventDefault();
				  e.stopPropagation();
				  console.log("drop");
				  var files = e.dataTransfer.files // 这里获取到用户拖放的文件
				  console.log('333333333333333333333333');
				  console.log(files);
				  // 其中 ajaxUpload是Ajax上传文件的函数
				  // uploadUrl是后端提供的上传地址, uploadCallback是上传后的回调函数，用于生成代码片段并插入编辑器
				  ajaxUpload('{:url(\'Upload/mdeditor\')}', files, uploadCallback);
				  return false;
				};
			},
            onfullscreen : function() {
			    $(".navbar").css("display","none");
			    $("#CreateUsers").css("display","none");
			    $(".KmoreInfo").css("display","none");
                $("#cate").css("display","none");
                $("#img").css("display","none");
                 //alert("onfullscreen");
                // console.log("onfullscreen =>", this, this.id, this.settings);
            },

            onfullscreenExit : function() {
                // alert("onfullscreenExit");
                $(".navbar").css("display","block");
                $("#CreateUsers").css("display","block");
                $(".KmoreInfo").css("display","block");
                $("#cate").css("display","block");
                $("#img").css("display","block");
                // console.log("onfullscreenExit =>", this, this.id, this.settings);
            }
		});


		$("#append-btn").click(function(){
			$.get("{:config('web.cdn')}/static/index/editormd/test.md", function(md){
				testEditor.appendMarkdown(md);
			});
		});
	});
	//ajax 上传文件
	function ajaxUpload(uploadUrl, files, callback) {
	  console.log("my ajax upload begin");
	  console.log(files[0]);
	  var formData = new FormData();
	  formData.append('file', files[0]);
	  // 可以添加其他需要传给后端的参数
	  $.ajax({
		url: uploadUrl,
		type: 'POST',
		data: formData,
		cache: false,
        contentType: false,    //不可缺
        processData: false,    //不可缺
		dataType: 'json',
		success: function(data) {
		  console.log("result:", data);
		  callback(data);
		},
		complete: function(data) {
		}
	  });

	  return false;
	}

	function uploadCallback(data) {
	  var url = data.url; // 依据后端返回的数据格式而定
	  var link = url;
	  if (!url) return false;

	  var alt = "";
	  var cm = testEditor; // myEditormd是用editormd函数创建的编辑器对象，这里假设myEditor是全局变量
	  var cursor = cm.getCursor(); // 获取光标位置
	  if (url.endsWith(".mp4")) { // 如果是是视频
		var videoHtml = '<video class="video-js" controls preload="auto" width="100%" poster="" data-setup=\'{"aspectRatio":"16:9"}\'>\
	<source src="' + url + '" type=\'video/mp4\' >\
	<p class="vjs-no-js">\
	To view this video please enable JavaScript\
	</p>\
	</video>';
		videoHtml = "\n" + videoHtml + "\n"; // videoHtml是生成的HTML视频代码片段
		cm.replaceSelection(videoHtml); // 插入到编辑器中
		cm.setCursor(cursor.line, cursor.ch + 2);
		return;
	  }
	  // 以下是对图片上传结果的处理，引用原image-upload插件的代码
	  var altAttr = (alt !== "") ? " \"" + alt + "\"" : "";
	  if (link === "" || link === "http://")
	  {
		cm.replaceSelection("![" + alt + "](" + url + altAttr + ")");
	  }
	  else
	  {
		cm.replaceSelection("[![" + alt + "](" + url + altAttr + ")](" + link + altAttr + ")");
	  }

	  if (alt === "") {
		cm.setCursor(cursor.line, cursor.ch + 2);
	  }
	}

layui.use('form', function(){
	var form = layui.form;
	//文章提交保存
	form.on('submit(info)', function(data){
		var url = "{:url('article/save')}";
		var loading = layer.load();
		$.post(url,data.field,function (e) {
			if(e.code ==200){
				success(e.msg + '请手动刷新网页或者查看首页');
				//setTimeout("location.reload()",2000);
				layer.close(loading);
			}else {
				error(e.msg);
			}
		})
		return false;
	});
    form.on('submit(draft)', function(data){
        var temp = data.field;
        temp.status = 2; //草稿
        var url = "{:url('article/save')}";
        $.post(url,temp,function (e) {
            if(e.code ==200){
                success(e.msg);
                //setTimeout("location.reload()",2000);
            }else {
                error(e.msg);
            }
        })

    });

	//ajax获取分类数据
    function getCate(pid,name,id){
        var url = "{:url('article/get_cate')}";
        $.post(url,{pid:pid},function (e) {
            //console.log(e)
			var html="";
			var data = e.data;
			html += '<select name="cate_id" id="'+name+'_id" lay-filter="'+id+'" lay-verify="required">';
			html += '<option value="">请选择</option>';
			for (var i = 0;i<data.length;i++){
			    html += "<option  value='"+data[i].id+"'>"+data[i].name+"</option>";
			}
			if(data.length > 0){
				$("#"+id).html(html);
			}else {
				$("#"+id).children().remove();
			}
			html += '</select>';
			form.render();
        })

    };
    getCate(0,'cate_id','cate1');

	//目前系统无三级分类，故二级即可实现需求
    form.on('select(cate1)', function(data){
        //console.log(data.elem); //得到select原始DOM对象
        //console.log(data.value); //得到被选中的值
		//console.log(data.othis); //得到美化后的DOM对象
		getCate(data.value,"cate_id",'cate2')
    });
});

	/**
	 * 粘贴上传图片
	 */
	$("#test-editormd").on('paste', function (ev) {
		var data = ev.clipboardData;
		var items = (event.clipboardData || event.originalEvent.clipboardData).items;
		for (var index in items) {
			var item = items[index];
			if (item.kind === 'file') {
				var blob = item.getAsFile();
				var reader = new FileReader();
				reader.onload = function (event) {
					var base64 = event.target.result;
					//ajax上传图片
					$.post("{:url('Upload/paste_up')}",{base:base64}, function (ret) {
						layer.msg(ret.msg);
						if (ret.code == 1) {
							//新一行的图片显示
							//editor.insertValue("\n![" + ret.data.title + "](" + ret.data.path + ")");
							uploadCallback(ret);
						}
					});
				}; // data url!
				var url = reader.readAsDataURL(blob);
			}
		}
	});



</script>
{/block}